package co.dianjiu.nio;

import co.dianjiu.nio.server.NIOServerHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;

@SpringBootApplication
public class Application implements CommandLineRunner {
    private Selector selector ;

    @Value("${nio.port}")
    private int port;

    @Value("${nio.url}")
    private String url;

    public static void main(String[] args) {
        System.setProperty("cfg.env","local");
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        selector = Selector.open(); //nio是通过selector管理多个管道的，所以一定要有selector
        ServerSocketChannel ssc = ServerSocketChannel.open();//开启一个服务端
        ssc.configureBlocking(false);//设置服务socket非阻塞
        ssc.bind(new InetSocketAddress(port));//绑定监听端口
        System.out.println("服务端已经启动，监听端口为：" + port);
        ssc.register(selector, SelectionKey.OP_ACCEPT);//绑定selector，此时只需在意 打开 OP_ACCEPT事件，相当于传统socket中的accept()操作
        new NIOServerHandler(selector).listen(); //监听连接事件方法
    }
}
